package com.android.webserver.util;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.android.webserver.R;
import com.android.webserver.db.DatabaseOpenHelper;
import com.android.webserver.db.WebApplication;
import com.android.webserver.tornado.HTTP;
import com.android.webserver.tornado.HTTPException;
import com.android.webserver.tornado.Request;
import com.android.webserver.tornado.Response;
import com.android.webserver.tornado.Tornado;

/**
 * @author Baptiste GOURDIN
 *
 */
public class InternalPages
{
	
	private static void getStartPage(Context context, Response response)
	{
		DatabaseOpenHelper db = new DatabaseOpenHelper(context);
		Cursor c = db.getApplications();
		c.moveToFirst();
		
		
		response.setHTTPStatusCode(HTTP.OK);
		response.HTMLContent = "<html><head>" + "<title>Android start page</title>"
				+ "</head><body>" + "<center>" + "<h1>Web Applications</h1>";
		
		while (c.isAfterLast() == false) {
			String appName = c.getString(1);
			String appPath = c.getString(2);
			boolean enabled = (c.getInt(3) == 1);
			if (enabled)
				response.HTMLContent += "<p><a href=\""+appPath+"\">"+ TextUtils.htmlEncode(appName) +"</a></p>";

			c.moveToNext();
			
		}
		c.close();
		db.close();
		response.HTMLContent  += "</center></body></html>";
		response.addHeader("Content-Length: " + response.HTMLContent.length());
		response.addHeader("Content-Type: text/html");
	}
	
	private static void getJs(Context context, Response response, int ressourceId)
			throws HTTPException
	{
		RawRessourceUtil.getRawTextFile(context, response, ressourceId);
		response.modifyHeader("Content-Type: text/javascript");
	}

	public static boolean isInternalPage(Context context, Request request,
			Response response) throws HTTPException
	{
		String fullPath = request.getFullPath();

		if (fullPath.equals("/auth"))
		{
			Tornado.androidService.sessions.verifyPasswordAndCreateSession(request,
					response);
			Log.d("WebServer", "Auth OK");
			return true;
			}
		else if (fullPath.equals("") || fullPath.equals("/"))
		{
			getStartPage(context, response);
			return true;
			}
		else
			if (fullPath.equals("/sha1.js"))
				getJs(context, response, R.raw.sha1);
			else
				if (fullPath.equals("/authentify.js"))
					getJs(context, response, R.raw.authentication);
				else
					if (fullPath.equals("/favicon.ico"))
						RawRessourceUtil.getPicture(context, response, R.drawable.icon);
					else
						return false;
		return true;
	}
}
